const vscode = require('vscode');
const path = require('path');
const hiSmartLiteEx = require('../../hiSmartLiteEx');
const AccountClass = require('../../util/accountClass');
const giteeApi = require('../../rest/giteeApi');
const MenuItemProvider = require('../menu/menuItemProvider');
const i18n = require('i18next');
const settingHandler = require('../../util/settingHandler');
const SettingHandler = require('../../util/settingHandler');

class LoginClass {
  constructor(webview) {
    this.webview = webview;
    this.accountInfo = {};
  }

  // 判断gitee是否登录
  async getIsGiteeLogin() {
    const accountClass = new AccountClass();
    const accountInfo = accountClass.getGiteeLoginInfo();
    let isLogin = accountInfo && accountInfo.giteeLogin;
    const data = {
      isLogin: isLogin,
      userNum: isLogin ? accountInfo.giteeLogin : '',
    };
    // 登录过期，清空页面
    const accessToken = await accountClass.getAccessToken();
    if (!accessToken) {
      data.isLogin = false;
    }
    const userInfo = await accountClass.getGiteeLoginInfo();
    if (this.webview) {
      this.webview.postMessage({
        command: 'returnIsGiteeLogin',
        data: { userInfo, ...data }
      });
    }
  }

  // 点击登录
  async handleLogin(message) {
    this.accountInfo = {};
    const paramObj = message.paramObj;
    if (!paramObj.userNum || !paramObj.password) {
      vscode.window.showErrorMessage('Please Input email and password');
    }
    const accountClass = new AccountClass();
    const username = paramObj.userNum;
    const password = paramObj.password;
    const authorization = accountClass.generateAuthorization(username, password);
    this.accountInfo.Authorization = authorization;
    this.accountInfo.giteeLogin = username;
    await accountClass.setAuthValue(this.accountInfo);
    if (!await this.loginProcess(username, password)) {
      return;
    }
    if (this.isInstallReviewPlugin()) {
      // 刷新review插件数据
      await vscode.commands.executeCommand('HiSmartLiteReview.setTreeViewData');
    }
    const userInfo = await accountClass.getGiteeLoginInfo();
    this.webview.postMessage({
      command: 'returnIsGiteeLogin',
      data: {
        isLogin: true,
        userNum: username,
        userInfo: userInfo
      }
    });
  }

  async loginProcess(username, password) {
    const clientId = new settingHandler().getClientId();
    const clientSecret = new SettingHandler().getClientSecret();
    try {
      // 校验邮箱密码
      let res = await giteeApi.getAccessToken(username, password, clientId, clientSecret, hiSmartLiteEx.scope);
      const accessToken = res.data.access_token;
      // 校验token
      const result = await giteeApi.getUserData(accessToken);
      this.accountInfo.accessToken = accessToken;
      // 存储登录信息
      const accountClass = new AccountClass();
      await accountClass.setAuthValue(this.accountInfo);
      await accountClass.setGiteeUserInfo(result.data);

    } catch (error) {
      this.webview.postMessage({
        command: 'incorrectUsernameOrPassword',
        data: {
          isIncorrectUsernameOrPassword: true,
        }
      });
      return false;
    }
    return true;
  }

  isInstallReviewPlugin() {
    const reviewPluginInfo = vscode.extensions.getExtension('gitee.hismartlite-review');
    return reviewPluginInfo !== undefined;
  }

  // 取消登录
  async cancelLogin() {
    // 将登录信息从globalState 删除
    new MenuItemProvider().initMenu();
    new AccountClass().clearAccountData();
    if (this.isInstallReviewPlugin()) {
      // review插件数据清理
      await vscode.commands.executeCommand('HiSmartLiteReview.clearTreeView');
    }
    if (this.webview) {
      this.webview.postMessage({
        command: 'returnIsGiteeLogin',
        data: { isLogin: false }
      });
    }
  }

  // 根据鉴权信息刷新token
  async refreshAccessToken() {
    const clientId = new settingHandler().getClientId();
    const clientSecret = new SettingHandler().getClientSecret();
    let accessToken = '';
    const accountClass = new AccountClass();
    let userNum = '';
    try {
      userNum = accountClass.getGiteeLoginInfo().giteeLogin;
      if (!userNum) {
        vscode.window.showInformationMessage(i18n.t('hismartlite.foundation.loginExpired'), i18n.t('confirm')).then(async result => {
          if (result === i18n.t('confirm')) {
            this.cancelLogin();
            vscode.commands.executeCommand('HiSmartLiteFoundation.openLoginWebview');
          }
        });
        return accessToken;
      }
    } catch (error) {
      console.error('getGiteeLoginInfo fail, reason:', error);
    }
    try {
      const userInfo = atob(accountClass.getAuthorization(userNum));
      const username = userInfo.split(':')[0];
      const password = userInfo.split(':').slice(1).join(':');
      const res = await giteeApi.getAccessToken(username, password, clientId, clientSecret, hiSmartLiteEx.scope);
      accessToken = res.data.access_token;
      console.log('refresh--', accessToken);
      // 更新存储
      accountClass.setAccessToken(username, password, accessToken);
    } catch (error) {
      console.error('refreshAccessToken fail, reason:', error);
    }
    return accessToken;
  }

  // 获取存储的accessToken
  async getAccessToken(showInformation) {
    const accountClass = new AccountClass();
    const accessToken = accountClass.getAccessToken();
    console.log('get--', accessToken);
    if (!accessToken && showInformation) {
      // 提示用户登录
      vscode.window.showInformationMessage(i18n.t('hismartlite.foundation.loginExpired'), i18n.t('confirm')).then(async result => {
        if (result === i18n.t('confirm')) {
          this.cancelLogin();
          vscode.commands.executeCommand('HiSmartLiteFoundation.openLoginWebview');
        }
      });
    }
    return accessToken;
  }
}

module.exports = LoginClass;